let _ = require('lodash'),
  {genCodeObj,sendRes,genNoErrorCodeObj} = require('../helper/util'),
  errCode = require('../../conf/errorCode'),
  logger = require('../helper/logger'),
  cst     = require('../../conf/const');
  service = require('../services/authService');

var tagLogger = new logger.TagLogger('AUTH_CONTROLLER');
const COMMON_COOKIE_OPTIONS = {
  domain: cst.LOGIN_COOKIE_DOMAIN,
  path: cst.LOGIN_COOKIE_PATH,
  maxAge: cst.COMMON_COOKIE_MAX_AGE,
};
const LOGIN_COOKIE_OPTIONS = _.merge({}, COMMON_COOKIE_OPTIONS, {
  signed: true,
  maxAge: cst.LOGIN_COOKIE_MAX_AGE,
});
const LOGOUT_COOKIE_OPTIONS = _.merge({}, LOGIN_COOKIE_OPTIONS, {maxAge: 0});
const INTEGER_REGEXP = /^\d+$/;
var tagLogger = new logger.TagLogger('AUTH_CONTROLLER');
var clearLogin = (req, res) => {
  res.clearCookie(cst.LOGIN_SIGNATURE, LOGOUT_COOKIE_OPTIONS);
};
var setLogin = (req, res) => {
  res.cookie(cst.LOGIN_SIGNATURE, Date.now(), LOGIN_COOKIE_OPTIONS);
};
var isLogin = (req, res) => {
  return (
    req.signedCookies &&
    INTEGER_REGEXP.test(req.signedCookies[cst.LOGIN_SIGNATURE])
  );
};
var refreshLogin = (req, res) => {
  res.cookie(
    cst.LOGIN_SIGNATURE,
    req.signedCookies[cst.LOGIN_SIGNATURE],
    LOGIN_COOKIE_OPTIONS,
  );
};

exports.login = function(req, res, next) {
  tagLogger.debug('login');
  var name = req.body.name,
    passwd = req.body.passwd;
  service.checkAuth(name, passwd, (err, userObj) => {
    tagLogger.debug(`checkAuth, userObj[${JSON.stringify(userObj)}]`);
    if (userObj) {
      if(userObj.status == 1){
        return sendRes(req, res, genCodeObj(errCode.LOGIN_API, errCode['USER_FORBID_ERROR']));
      }
      service.upsertUser(userObj.accountName, (err, userIdObj) => {
        var rslt = null;
        if (err == null) {
          setLogin(req, res);
          res.cookie('userId', userObj.id, COMMON_COOKIE_OPTIONS);
          res.cookie('name', userObj.accountName, COMMON_COOKIE_OPTIONS);
          rslt = genNoErrorCodeObj();
        } else {
          tagLogger.error(
            `login, upsertUser[${util.transErrNo(err['errNo'])}]`,
          );
          rslt = genCodeObj(errCode.LOGIN_API, err['errNo']);
        }

        sendRes(req, res, rslt);
      });
    } else {
      tagLogger.warn(`login, fail errNo[${err['errNo']}]`);
      sendRes(req, res, genCodeObj(errCode.LOGIN_API, err['errNo']));
    }
  });
};

exports.logout = function(req, res, next){
  tagLogger.debug('logout');
  clearLogin(req, res);
  res.clearCookie('name',        LOGOUT_COOKIE_OPTIONS);
  res.clearCookie('userId',      LOGOUT_COOKIE_OPTIONS);
  res.redirect('/login');
  //sendRes(req, res, genNoErrorCodeObj());
};

exports.showSession = function(req, res, next){
  var str = `cookie[${JSON.stringify(req.cookies)}], signedCookies[${JSON.stringify(req.signedCookies)}], session[${JSON.stringify(req.session)}]`;
  tagLogger.debug(`showSession, cookie[${JSON.stringify(req.cookie)}], signedCookies[${JSON.stringify(req.signedCookies)}], session[${JSON.stringify(req.session)}]`);
  sendRes(req, res, str);
};

exports.checkLogin = function(req, res, next){
  tagLogger.debug('checkLogin');
  if(isLogin(req, res)){refreshLogin(req, res); next(); }
  else{ sendRes(req, res, genCodeObj(errCode.ANY_API, errCode.NOT_LOGIN_ERROR)); }
};

